package pers.cj.pdos.exception;


import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import pers.cj.pdos.entity.ExceptionLog;
import pers.cj.pdos.service.IExceptionLogService;
import pers.cj.pdos.utils.Logger;
import pers.cj.pdos.utils.UuidUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Autowired
    private IExceptionLogService exceptionLogService;


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        exception.printStackTrace();
        String msg;
        //判断异常类型
        if (exception instanceof CustomException) {
            //如果是自定义异常，就从异常里面取出错误信息
            CustomException customException = (CustomException)exception;
            msg = customException.getErrMsg();
        } else if(exception instanceof UnauthorizedException) {
            msg = "无此权限";
        } else {
            //如果是运行时异常，则取错误的堆栈信息
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            exception.printStackTrace(printWriter);
            msg = stringWriter.toString();
        }

        ModelAndView modelAndView = new ModelAndView();
        // 判断是否 Ajax 请求
        if ((request.getHeader("accept").indexOf("application/json") > -1 ||
                (request.getHeader("X-Requested-With") != null &&
                        request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))){
            /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */
            FastJsonJsonView view = new FastJsonJsonView();
            Map<String, Object> attributes = new HashMap<>();
            attributes.put("code", 2);
            attributes.put("msg", msg);
            view.setAttributesMap(attributes);
            modelAndView.setView(view);
        } else {
            if (msg.equals("无此权限")){
                modelAndView.setViewName("refuse");
            } else {
                //返回一个友好的错误页面，并显示错误消息
                modelAndView.addObject("msg",msg);
                modelAndView.setViewName("error");
            }
        }

        //日志写入数据库
        ExceptionLog log = new ExceptionLog();
        log.setId(UuidUtils.getUUID());
        log.setMsg(msg);
        log.setTime(new Date());
        log.setClassName(exception.getClass().getName());
        exceptionLogService.save(log);
        return modelAndView;
    }
}
